﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.UI;
using System.Web.UI.WebControls;
using System.Drawing;
using System.Drawing.Imaging;
using System.Globalization;
using System.Web.Security;
using System.IO;
using System.Threading;
using WCF;



namespace geekmeet
{
    public partial class EditProfile : System.Web.UI.Page
    {
        /// <summary>
        /// This page lets a user edit his/her profile. The fields are objects that holds info about the users 
        /// Guid, profile, all interests that a user can choose from and the interest that the user 
        /// has chosen. The Geekmeetservice object is the webservice that connects to the database.
        /// On page load we check the querystring, that tells us if the user is "old" and just want to 
        /// edit his info, or if its a new user that fills out the form for the first time.
        /// </summary>
        Guid loggedInUserGUID = (Guid) Membership.GetUser().ProviderUserKey;
        ProfileComposite userProfile;
        GeekMeetService wcf = new GeekMeetService();
        List<InterestComposite> userInterests;
        List<InterestComposite> allInterests;

        protected void Page_Load(object sender, EventArgs e)
        {
            FillLocations();
            GetInterests();
            userProfile = wcf.GetProfile(loggedInUserGUID);
            LblFileErrorMessage.Text = "";
            LblErrorSaveProfile.Text = "";
            
            //Checks if the page is rendered for the first time
            if (!IsPostBack)
            {
                FillDates();
               

                if (Request.QueryString["action"] == ("RegisterNewUser"))
                {
                    RedigeraProfilRubrik.Text = "Registrera ny profil";
                    LoadProfileImage();
                }
                else
                {
                    RedigeraProfilRubrik.Text = "Redigera profil";
                    GetProfileData();
                    LoadProfileImage();
                }
            }
        }
        /// <summary>
        /// Fills a combobox with a list of countries to choose from. 
        /// Uses asp.nets classes RegionInfo and Cultureinfo to do that. 
        /// </summary>
        private void FillLocations()
        {
            RegionInfo country = new RegionInfo((new CultureInfo("sv-SE", false)).LCID);
            List<string> countryNames = new List<string>();

            //Get country names from the CultureInfo installed in windows
            foreach (CultureInfo cul in CultureInfo.GetCultures(CultureTypes.SpecificCultures))
            {
                country = new RegionInfo((new CultureInfo(cul.Name, false)).LCID);
                countryNames.Add(country.DisplayName.ToString());
            }

            //Assign all Country names to IEnumerable
            IEnumerable<string> nameAdded = countryNames.OrderBy((names) => names).Distinct();

            foreach (string item in nameAdded)
            {
                ddlCountries.Items.Add(item); //Add items to DropDownList
            }
        }
        /// <summary>
        /// Gets user interests, and adds the rest of the interests to the list of 
        /// available interests.
        /// </summary>
        private void GetInterests()
        {
            ddlAvailableInterests.Items.Clear();
            userInterests = wcf.GetUserInterests(loggedInUserGUID);
            allInterests = wcf.GetAllInterests();

            foreach (InterestComposite i in allInterests)
            {
               // Check if users already has current interest
                InterestComposite found = userInterests.SingleOrDefault(x => x.InterestID == i.InterestID);
               
               // Current interest is not in this user's interests, so add it to available interests
                if (found == null)
                {
                    ListItem li = new ListItem(i.InterestName, i.InterestID.ToString());
                    ddlAvailableInterests.Items.Add(li);
                }
                else
                {
                    // Else call javascript to add interest to current
                    Page.ClientScript.RegisterStartupScript(
                   this.GetType(), "addInterest"+i.InterestName, "addInterest('" + i.InterestName + "','" + i.InterestID + "');", true);
                }

            }

            if (ddlAvailableInterests.Items.Count == 0)
            {
                ddlAvailableInterests.Items.Add("Du är intresserad av allt!");
                ddlAvailableInterests.Enabled = false;
            }
        }
        /// <summary>
        /// Gets the users info and displays it
        /// </summary>
        private void GetProfileData()
        {
           
                txtFirstName.Text = userProfile.FirstName;
                txtLastName.Text = userProfile.LastName;
                txtProfileText.Text = userProfile.Text;
                txtCity.Text = userProfile.City;
                
                // Select gender
                ddlGender.SelectedValue = userProfile.Gender;

                // Select preselected country
                if (userProfile.Country == "")
                    ddlCountries.SelectedIndex = 0;
                else
                    ddlCountries.SelectedValue = userProfile.Country;

                
                
            
        }

        private void LoadProfileImage()
        {
            // Load user image
            imgProfilePicture.ImageUrl = "~/images/profilePictures/" + loggedInUserGUID
                + ".jpg";
            imgProfilePicture.DataBind();
        }
        /// <summary>
        /// Fills the date-comboboxes with info. If the user already has a profile, the birthdate is chosen
        /// </summary>
        private void FillDates()
        {
            // populate the days drop down
            for (int days = 1; days < 32; days++)
            {
                ListItem li = new ListItem();
                li.Text = days.ToString();
                li.Value = days.ToString();
                ddlDay.Items.Add(li);
            }

            // populate the month drop down
            DateTime d = new DateTime(1977,01,01);
            for (int month = 1; month < 13; month++)
            {
                ListItem li = new ListItem();
                li.Text = CultureInfo.CurrentCulture.DateTimeFormat.GetMonthName(month);
                li.Value = month.ToString();
                ddlMonth.Items.Add(li);
            }
            // populate the years drop down
            int thisYear = System.DateTime.Now.Year;
            int startYear = thisYear - 18;
            for (int year = startYear; year > startYear - 100; year--)
            {
                ListItem li = new ListItem();
                li.Text = year.ToString();
                li.Value = year.ToString();
                ddlYear.Items.Add(li);
            }

            if (Request.QueryString["action"] != ("RegisterNewUser"))
            {
                // Select birthdate from database
                ddlYear.SelectedValue = userProfile.BirthDate.Year.ToString();
                ddlMonth.SelectedIndex = userProfile.BirthDate.Month - 1; // Index starts at 0
                ddlDay.SelectedIndex = userProfile.BirthDate.Day - 1; // Index starts at 0;
            }
        }
        /// <summary>
        /// Triggers when user clicks on the button to save the profilepicture.
        /// </summary>
        /// <param name="sender"></param>
        /// <param name="e"></param>
        protected void BtnSavePicture_Click(object sender, EventArgs e)
        {
            //Set limit for file
            int sizeLimit = 5242880;
            //Check if there is a file chosen
            if (UploadProfilepicture.HasFile)
            {
                //Check if pic is within limit
                if (UploadProfilepicture.PostedFile.ContentLength <= sizeLimit && UploadProfilepicture.PostedFile.ContentType == "image/jpeg")
                {
                        string path = Server.MapPath("~/images/profilePictures/" + loggedInUserGUID + ".jpg");
                        UploadProfilepicture.SaveAs(path);
                        Response.Redirect("EditProfile.aspx");
                    }
                    else
                    {
                        LblFileErrorMessage.Text = "Bilden måste vara av typen jpeg och max 5mb.";
                    }
                                             
                }
               
            }
        
        
        protected void btnSubmit_Click(object sender, EventArgs e)
        {
            SaveProfile();
        }
        /// <summary>
        /// Saves the users profile if validation is ok.
        /// </summary>
        private void SaveProfile()
        {
            if (Page.IsValid)
            {
                try
                {
                    // Personal info
                    int selectedYear = int.Parse(ddlYear.SelectedValue);
                    int selectedMonth = int.Parse(ddlMonth.SelectedValue);
                    int selectedDay = int.Parse(ddlDay.SelectedValue);

                    userProfile.FirstName = txtFirstName.Text;
                    userProfile.LastName = txtLastName.Text;
                    userProfile.BirthDate = new DateTime(selectedYear, selectedMonth, selectedDay);
                    userProfile.Text = txtProfileText.Text;
                    userProfile.City = txtCity.Text;
                    userProfile.Country = ddlCountries.SelectedValue;
                    userProfile.Gender = ddlGender.SelectedValue;


                    // Call wcf to update
                    wcf.EditProfile(userProfile);
                    
                    // Get selected interests
                    string hidden_selectedInterestsValue = Request.Form["hidden_selectedInterests"];
                    if (hidden_selectedInterestsValue != "")
                        hidden_selectedInterestsValue = hidden_selectedInterestsValue.Remove(
                            hidden_selectedInterestsValue.Length - 1, 1);

                    string[] interestIDs;
                    List<int> interestIDsToSave = new List<int>();

                    interestIDs = hidden_selectedInterestsValue.Split(',').ToArray();

                    foreach (string interest in interestIDs)
                    {
                        int interestID;

                        // For security, check if provided value is valid interestID
                        if (int.TryParse(interest, out interestID) &&
                            allInterests.Where(x => x.InterestID == interestID) != null)
                        {
                            // If yes, add to array of interests
                            // Array posts start at 0...
                            interestIDsToSave.Add(interestID);
                        }

                    }

                    // Save and reload page
                    wcf.ModifyUserInterests(loggedInUserGUID, interestIDsToSave);
                    Response.Redirect(Request.RawUrl, false);
                }
                catch (Exception ex)
                {
                    LblErrorSaveProfile.Text = "Din profil kunde inte sparas: " + ex.Message;
                }
            }
        }

        public Size NewImageSize(int OriginalHeight, int OriginalWidth, double FormatSize)
        {
            Size NewSize;
            double tempval;

            if (OriginalHeight > FormatSize && OriginalWidth > FormatSize)
            {
                if (OriginalHeight > OriginalWidth)
                    tempval = FormatSize / Convert.ToDouble(OriginalHeight);
                else
                    tempval = FormatSize / Convert.ToDouble(OriginalWidth);

                NewSize = new Size(Convert.ToInt32(tempval * OriginalWidth), Convert.ToInt32(tempval * OriginalHeight));
            }
            else
                NewSize = new Size(OriginalWidth, OriginalHeight); 
            
            return NewSize;
        }
    }
}